﻿#include "FITKRadiossSurfaceSeg.h"
#include "FITKRadiossMeshModel.h"
#include "FITKRadiossNodesParts.h"
#include "FITK_Interface/FITKInterfaceModel/FITKAbstractElement.h"
#include <QSet>

namespace Radioss
{
    FITKRadiossSurfaceSeg::FITKRadiossSurfaceSeg()
        : FITKAbstractRadiossSurface()
    {
       // this->isInternal(false);
    }

    FITKAbstractRadiossSurface::RadiossSurfaceType FITKRadiossSurfaceSeg::getRadiossSurfaceType()
    {
        return FITKRadiossSurfaceSeg::RadiossSurfaceType::RST_SEG;
    }

    void FITKRadiossSurfaceSeg::addSurface(QList<int> surfNodesIDs)
    {
        FITKRadiossMeshModel* meshModel = this->getRadiossMeshModel();
        if(meshModel == nullptr) return;
        FITKRadiossPartManager* partManager = meshModel->getPartsManager();
        if(partManager == nullptr) return;
        FITKRadiossMeshTopo* meshTopo = meshModel->getMeshTopo();
        if(meshTopo == nullptr) return;

        QList<Interface::FITKAbstractElement*> elementList = meshTopo->getNodeElements(surfNodesIDs.first());
        QSet<Interface::FITKAbstractElement*> intersection = elementList.toSet();
        for (int i = 1; i < surfNodesIDs.size(); i++)
        {
            const int nodeID = surfNodesIDs.at(i);
            QList<Interface::FITKAbstractElement*> nodeElementList = meshTopo->getNodeElements(nodeID);
            // 求交集,找到包含所有节点的单元
            QSet<Interface::FITKAbstractElement*> set2 = nodeElementList.toSet();
            intersection &= set2;
        }

        if (intersection.isEmpty()) return;

        // 取第一个元素作为代表
        Interface::FITKAbstractElement* elementPtr = intersection.values().first();
        if (elementPtr == nullptr) return;
        int faceIndex = elementPtr->getFaceIndexNorUnSen(surfNodesIDs, true);
        int eleID = elementPtr->getEleID(); 
        this->addElementSurface(eleID, faceIndex);
    }

    QList< QList<int> > FITKRadiossSurfaceSeg::getSurface(int element, const bool & lowerOrder)
    {
        QList< QList<int> > res;
        QList<int> faceIndexList = _elementSurface.values(element);
        if(faceIndexList.isEmpty()) return res;
         FITKRadiossMeshModel* meshModel = this->getRadiossMeshModel();
        if(meshModel == nullptr) return res;
        FITKRadiossPartManager* partManager = meshModel->getPartsManager();
        if(partManager == nullptr) return res;
        //找到对应的单元
        Interface::FITKAbstractElement* elementPtr = partManager->getElementByID(element).second;
        if(elementPtr == nullptr) return res; 

        for (int i = 0; i < faceIndexList.size(); i++)
        {
            int faceIndex = faceIndexList.at(i);
            QList<int> faceNodes = elementPtr->getFace(faceIndex, lowerOrder);
            res.append(faceNodes);
        }
        return res;
    }

    QList<int> FITKRadiossSurfaceSeg::getAllElement() const
    {
        return _elementSurface.keys();
    }

} // namespace Radioss
